<template>
  <div class="tree-box">
    <el-tree
      ref="treeRef"
      highlight-current
      :props="prop"
      :indent="0"
      node-key="tenantId"
      :data="treeData"
      :default-expand-all="true"
      style="width: 100%"
      :filter-node-method="filterNode"
      :expand-on-click-node="false"
      :default-expanded-keys="defaultkeys"
      draggable
      :allow-drop="allowDrop"
      :allow-drag="allowDrag"
      @node-drag-start="handleDragStart"
      @node-drag-over="handleTreeDragOver"
      @node-drop="handleTreeDrop"
    >
      <template #default="{ node, data }">
        <div
          class="tree_item pointer"
          :style="{
            width: node.isLeaf ? 'calc( 100% - 10px)' : 'calc( 100% - 24px)',
            'margin-left': node.isLeaf ? '10px' : '0px',
          }"
          @click="handleClick(node, data, $event)"
          :data-id="JSON.stringify(data.id)"
          :data-type="JSON.stringify(data.type)"
        >
          <div class="label_item">
            <img src="@/assets/common/部门目录-打开.png" alt="节点图标" class="node-icon" />

            <span class="tree-lable" :id="data.id" :title="node.label">
              {{ node.label }}

              <span
                v-if="node.level === 1"
                style="font-family: Microsoft YaHei; color: #666666; font-size: 12px"
                >({{ num }})</span
              >
            </span>
          </div>
          <div class="btns" v-if="node.level !== 1 && node.isCurrent && btnclick">
            <img
              src="@/assets/common/delete-table.png"
              class="vam"
              @click.stop="btnClick(node, 'del')"
              alt="删除"
            />
          </div>
        </div>
      </template>
    </el-tree>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onUpdated, nextTick } from 'vue'

// 定义组件接收的props
const props = defineProps([
  'treeData',
  'prop',
  'check',
  'del',
  'curtab',
  'showbox',
  'node',
  'expand',
  'defaultNode',
  'curNode',
  'picUrl',
  'isdraggable',
  'btnclick',
])

// 定义组件发出的事件
const emit = defineEmits(['handleClick', 'btnClick', 'handleTreeDrop'])

// 响应式数据
const treeRef = ref(null)
const selectlist = ref([])
const curId = ref('')
const curIdB = ref('')
const curIdC = ref('')
const defaultkeys = ref([])
const num = ref(0)

// 生命周期钩子 - 挂载后
onMounted(() => {
  try {
    curId.value = props.treeData[0].tenantId
  } catch (error) {
    console.error('Failed to initialize curId on mount:', error)
  }
})

// 生命周期钩子 - 更新后
onUpdated(() => {
  setCurrentNode()
  try {
    curId.value = props.treeData[0].tenantId
  } catch (error) {
    console.error('Failed to update curId on update:', error)
  }
})

// 处理节点点击事件
const handleClick = (node, data) => {
  if (node.level === 1) {
    curId.value = data.id
    curIdB.value = ''
    curIdC.value = node.id
  }
  if (node.level === 2) {
    curId.value = data.id
    curIdB.value = node.id
    curIdC.value = node.id
  }

  emit('handleClick', {
    data: data,
    node: node,
  })
}

// 更新子节点
const setChild = (key, data) => {
  if (treeRef.value) {
    treeRef.value.updateKeyChildren(key, data)
  }
}

// 筛选节点方法
const filterNode = (value, data) => {
  for (const e in data) {
    const name = data[e]
    if (e !== 'children' && name) {
      if (name.toString().toLowerCase().indexOf(value.toLowerCase()) !== -1) {
        return data
      }
    }
  }
}

// 执行筛选
const getFilter = (val) => {
  if (treeRef.value) {
    treeRef.value.filter(val)
  }
}

// 设置当前节点高亮
const setCurrentNode = () => {
  nextTick(() => {
    if (props.node && treeRef.value) {
      treeRef.value.setCurrentNode(props.node)
    }
  })
}

// 设置高亮节点
const setHighlight = (id) => {
  nextTick(() => {
    if (treeRef.value) {
      treeRef.value.setCurrentKey(id)
    }
  })
}

// 设置当前节点key
const setCurrentKey = (id) => {
  setTimeout(() => {
    if (treeRef.value) {
      treeRef.value.setCurrentKey(id)
      curId.value = id
    }
  }, 30)
}

// 按钮点击事件
const btnClick = (node, type) => {
  emit('btnClick', node, type)
}

// 允许放置
const allowDrop = (draggingNode, dropNode, type) => {
  // 允许放置在节点区域
  return type !== 'none'
}

// 允许拖拽
const allowDrag = () => {
  return props.isdraggable
}

// 处理拖拽开始
const handleDragStart = (draggingNode, event) => {
  // 创建自定义拖拽图像
  const dragImage = document.createElement('div')
  dragImage.textContent = draggingNode.label

  // 设置缩小后的样式
  dragImage.style.cssText = `
    width: 80px;
    padding: 4px;
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    font-size: 12px;
    opacity: 0.9;
    transform: scale(0.8);
    transform-origin: 0 0;
  `

  // 将元素添加到DOM（不可见位置）
  dragImage.style.position = 'fixed'
  dragImage.style.left = '-9999px'
  document.body.appendChild(dragImage)

  // 设置拖拽图像（偏移量根据实际调整）
  event.dataTransfer.setDragImage(dragImage, 40, 16) // 中心偏移

  // 拖拽完成后移除临时元素
  setTimeout(() => {
    document.body.removeChild(dragImage)
  }, 0)
}

// 处理树节点放置
const handleTreeDrop = (draggingNode, targetNode) => {
  emit('handleTreeDrop', { draggingNode, targetNode })
}

// 处理拖拽到树节点上
const handleTreeDragOver = (draggingNode, dropNode, event) => {
  event.preventDefault() // 允许放置
}

// 暴露方法给父组件
defineExpose({
  setChild,
  getFilter,
  setCurrentNode,
  setHighlight,
  setCurrentKey,
})
</script>

<style lang="scss" scoped>
:deep(.tree-box) {
  font-size: 12px !important;
  font-family: Microsoft YaHei;
  font-weight: 400;
  overflow-x: hidden;
  overflow-y: scroll;
  height: 100%;
  width: 100%;
}

.tree_item {
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .label_item {
    height: 28px;
    display: flex;
    align-items: center;
    width: calc(100% - 52px);

    img {
      width: 15.01px;
      height: 15.45px;
    }

    .tree-lable {
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      display: inline-block;
      width: calc(100% - 35px);
      line-height: 26px;
      font-family: Microsoft YaHei;
      color: #666666;
      font-size: 12px;
      margin-left: 8px;
    }
  }

  .btns {
    margin-right: 7px;

    .margin-r-15 {
      margin-right: 15px;
    }
  }
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background: #eef6f9 !important;
  color: #666666;
}

.node-icon {
  vertical-align: middle;
  margin-right: 6px;
  width: 16px;
}

// 向右小图标
.el-tree-node__content > .el-tree-node__expand-icon {
  &::before {
    left: -12px;
    top: 14px;
    border-color: transparent transparent transparent #aaaaaa;
  }
}

.el-tree-node__content > .expanded.el-tree-node__expand-icon {
  &::before {
    left: -17px;
    top: 17px;
    border-color: #aaaaaa transparent transparent;
  }
}

/****线条开始 */

// 自定义竖线

/* ------------------------------------ */
:deep(.el-tree-node__expand-icon.expanded) {
  transform: rotate(90deg) !important;
}

:deep(.el-tree-node__expand-icon) {
  color: #666666 !important;
}

:deep(.el-tree-node) {
  position: relative;
  padding-left: 0px;
}

// 节点有间隙，隐藏掉展开按钮
:deep(.el-tree-node__expand-icon.is-leaf) {
  display: none;
}

:deep(.el-tree-node__children) {
  padding-left: 16px;
}

:deep(.el-tree-node :last-child:before) {
  height: 38px;
}

:deep(.el-tree > .el-tree-node:after) {
  border-top: none;
}

:deep(.el-tree-node:before) {
  content: '';
  left: -4px;
  position: absolute;
  right: auto;
  border-width: 1px;
}

:deep(.el-tree-node:after) {
  content: '';
  left: -4px;
  position: absolute;
  right: auto;
  border-width: 1px;
}

:deep(.el-tree-node:before) {
  border-left: 1px dotted #888888;
  bottom: 0px;
  height: 100%;
  top: -26px;
  width: 1px;
}

:deep(.el-tree-node:after) {
  border-top: 1px dotted #888888;
  height: 20px;
  top: 13px;
  width: 20px;
}

:deep(.el-tree-node__content) {
  height: 28px !important;
}

.vam {
  vertical-align: middle;
}
</style>
